//
//  mySelfViewController.m
//  MagicBox
//
//  Created by dllo on 16/8/15.
//  Copyright © 2016年 dllo. All rights reserved.
// 159 9858 7329

#import "mySelfViewController.h"
#import "SecondHViewController.h" //生成自己的二维码
#import "QRCodeViewController.h"
#import "PedometerViewController.h" //计步器
#import "DrawingViewController.h"
#import "CalculatorViewController.h" // 计算器


#warning CC;
#import "LoadResigter_ViewController.h" // 登录和注册界面
#import "HadLogin_ViewController.h"  // 已经登录进入用户信息界面
#import "Find_ViewController.h" // 返回用
#import "EMSDK.h"  // 初始化SDK




static NSString *const myCell = @"CELL";

@interface mySelfViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic ,strong) UITableView *myTableView;
@property (nonatomic ,strong)  UIView* leftView;
@property (nonatomic ,strong) NSMutableArray *myArray;


#warning CC;
@property(nonatomic, strong) UIImageView *defaultLoadImageView;
@property(nonatomic, strong) UIButton *publishButton;
@property(nonatomic, strong) UIButton *collectionButton;
@property(nonatomic, strong) UIButton *historyButton;

@property(nonatomic, strong) UILabel *userNameLabel;



@end

@implementation mySelfViewController
    
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
  
    _leftView = [[UIView alloc] init];
    //把左侧边的view先隐藏
    _leftView.frame = CGRectMake(- SCREENWIDTH * 0.5, 0, SCREENWIDTH * 0.5, SCREENHEIGHT);
    _leftView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_leftView];
    
    UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [self.view addGestureRecognizer:pan];
    
  
    
    self.myArray = [NSMutableArray arrayWithObjects:@"二维码",@"扫一扫",@"计步器",@"画图",@"计算器",@"支付",@"注销", nil];
    
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH * 0.5, SCREENHEIGHT - 64)];
    [self.leftView addSubview:_myTableView];
    self.myTableView.backgroundColor = [UIColor lightGrayColor];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:myCell];
    
     self.title = @"我的";
    
    
    // Controller的配置
    [self config];
    
    // 上半部分登录界面
    [self creatUpHalf];

    
}


- (void)viewWillAppear:(BOOL)animated {
 
    
    [super viewWillAppear: animated];
    
    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    self.userNameLabel.text =userName;
    
    
    if([EMClient sharedClient].isLoggedIn){
        
        
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        
        
        NSString *userName = [[EMClient sharedClient] currentUsername];
        NSString *file = [path stringByAppendingPathComponent:userName];
        
        NSData *imageData = [NSData dataWithContentsOfFile:file];
        
        
        if (imageData == NULL)
        {
            
            self.defaultLoadImageView.image = [UIImage imageNamed:@"headerLogin.png"];
            
        }
        else
        {
            
            self.defaultLoadImageView.image = [UIImage imageWithData:imageData];
        }
        
        
        
    }else
    {
        self.defaultLoadImageView.image = [UIImage imageNamed:@"defaultIcon@3x.png"];
    }
    
    

    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:myCell];
    cell.textLabel.text = [self.myArray objectAtIndex:indexPath.row];
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.myArray.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 70;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        
        SecondHViewController *secondHVC = [[SecondHViewController alloc] init];
        secondHVC.second = [self.myArray objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:secondHVC animated:YES];
      
    }else if (indexPath.row == 1) {
        
        QRCodeViewController *qrcVC = [[QRCodeViewController alloc] init];
        qrcVC.qrCode = [self.myArray objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:qrcVC animated:YES];
        
    }else if (indexPath.row == 2){
        
        PedometerViewController *PedometerVC = [[PedometerViewController alloc] init];
         PedometerVC.Pedometer = [self.myArray objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:PedometerVC animated:YES];
        
    }else if (indexPath.row == 3) {
       
          DrawingViewController *DrawingVC = [[DrawingViewController alloc] init];
        DrawingVC.Drawing = [self.myArray objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:DrawingVC animated:YES];
        
    }else if (indexPath.row == 4) {
        
        CalculatorViewController *CalculatorVC = [[CalculatorViewController alloc] init];
        CalculatorVC.Calculator = [self.myArray objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:CalculatorVC animated:YES];

    }else if (indexPath.row == 5) {
        
    }
    if (indexPath.row == 6) {
        
        if ([EMClient sharedClient].isLoggedIn) {
            
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"确认退出登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                [[EMClient sharedClient] logout:YES];
                
            }];
            
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:action];
            [alert addAction:action2];
            [self presentViewController:alert animated:YES completion:^{
                
            }];
            
            
            
        }else
        {
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"请先登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                // 如果没有登录
                
                    //跳转到登录和注册界面
                    LoadResigter_ViewController *loadResigterVC = [[LoadResigter_ViewController alloc]init];
                    [self presentViewController:loadResigterVC animated:YES completion:nil];
                    
                               

                
            }];
            
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"我再想想" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:action];
            [alert addAction:action2];
            [self presentViewController:alert animated:YES completion:^{
                
            }];

        }
        
        
    }
    
    
}


- (void)handlePan:(UIPanGestureRecognizer*) recognizer {
    CGPoint translation = [recognizer translationInView:self.view];
    //增量后的x坐标位置
    CGFloat Xresult = translation.x + _leftView.frame.origin.x;
    
    //向右
    if (translation.x >= 0) {
        //leftView已全部拉出，则无法再向右
        if (_leftView.frame.origin.x >= 0 || Xresult >= 0) {
            _leftView.frame = CGRectMake(0, 0, SCREENWIDTH * 0.5, SCREENHEIGHT);
            
            return;
        }
    } else if (translation.x < 0) {//向左
        //leftView已全部收回，则无法再向左
        if (_leftView.frame.origin.x <= -SCREENWIDTH * 0.5 || Xresult <= -SCREENWIDTH * 0.5) {
            _leftView.frame = CGRectMake(-SCREENWIDTH * 0.5, 0, SCREENWIDTH * 0.5, SCREENHEIGHT);
            return;
        }
    }
    
    CGRect frame = _leftView.frame;
    frame.origin.x += translation.x;
    _leftView.frame = frame;
    
    //清空移动的距离，这是关键
    [recognizer setTranslation:CGPointZero inView:recognizer.view];
    
    //做弹回效果，以中轴为界限
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        if (_leftView.frame.origin.x > -SCREENWIDTH * 0.25) {
            [self closeView:NO];
        } else {
            [self closeView:YES];
        }
    }
}

- (void)closeView:(BOOL)close {
    if (close) {
        [self moveView:CGRectMake(-SCREENWIDTH * 0.5, 0, SCREENWIDTH * 0.5, self.view.frame.size.height)];
    } else {
        [self moveView:CGRectMake(0, 0, SCREENWIDTH * 0.5, SCREENHEIGHT)];
    }
}

- (void)moveView:(CGRect)frame {
    [UIView animateWithDuration:0.3 animations:^{
        _leftView.frame = frame;
    } completion:^(BOOL finished) {
        
    }];
    
}



-(void)config{
    
    self.navigationController.navigationBarHidden = YES;
    
    
    self.view.userInteractionEnabled = YES;
    
    
    UIImageView *backImage = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    backImage.image = [UIImage imageNamed:@"backImageOfUser.jpeg"];
    backImage.alpha = 0.5;
    [self.view addSubview:backImage];
}

// 上半部分登录界面
-(void)creatUpHalf{

    NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    self.userNameLabel.text =userName;
    
    
    
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(SCREENWIDTH / 2 - (SPACED * 8 + 6) / 2, SPACED * 10, SPACED * 8 + 6, SPACED * 8 + 6)];
    backView.layer.cornerRadius =(SPACED * 8 + 6) / 2;
    backView.layer.masksToBounds = YES;
    backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backView];
    
    // 登录按钮
    self.defaultLoadImageView = [[UIImageView alloc]init];
    self.defaultLoadImageView.frame = CGRectMake(0, 0, SPACED * 8, SPACED * 8);
    _defaultLoadImageView.center = backView.center;
    _defaultLoadImageView.layer.cornerRadius = SPACED * 4;
    _defaultLoadImageView.layer.masksToBounds = YES;
    [self.view addSubview:_defaultLoadImageView];
    
    
    // 用户设置
    UILabel *congfigUser = [[UILabel alloc]init];
    congfigUser.frame = CGRectMake(SCREENWIDTH - SPACED * 10, SPACED * 3, SPACED * 8, SPACED * 4);
    congfigUser.text = @"用户设置";
    congfigUser.textAlignment = 2;
    congfigUser.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:congfigUser];
    congfigUser.userInteractionEnabled = YES;
    
    
    
    // 点击手势
    UITapGestureRecognizer *defaultLoadTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headerIsLoadOrNot)];
    defaultLoadTap.numberOfTapsRequired = 1;
    self.defaultLoadImageView.userInteractionEnabled = YES;
    [congfigUser addGestureRecognizer:defaultLoadTap];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap)];
    tap.numberOfTapsRequired = 1;
    [self.defaultLoadImageView addGestureRecognizer:tap];
    
    
    // 发布按钮
    self.publishButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_publishButton];
    [self.publishButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SPACED * 4, SPACED * 4));
        make.centerX.equalTo(self.view.mas_centerX).offset(-self.view.center.x / 2);
        make.top.equalTo(self.defaultLoadImageView.mas_bottom).offset(SPACED * 5);
        
    }];
    [self.publishButton setBackgroundImage:[UIImage imageNamed:@"publish@3x.png"] forState:UIControlStateNormal];
    // 我的发布
    UILabel *pulishLabel  = [[UILabel alloc]init];
    pulishLabel.font = [UIFont systemFontOfSize:15];
    pulishLabel.text = @"我的发布";
    pulishLabel.textAlignment = 1;
    [self.view addSubview:pulishLabel];
    [pulishLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SPACED * 10, SPACED * 4));
        make.centerX.equalTo(self.publishButton.mas_centerX);
        make.top.equalTo(self.publishButton.mas_bottom).offset(SPACED);
        
    }];
    
    
    
    // 我的收藏
    
    self.collectionButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_collectionButton];
    [self.collectionButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SPACED * 4, SPACED * 4));
        make.centerX.equalTo(self.view.mas_centerX).offset(0);
        make.top.equalTo(self.defaultLoadImageView.mas_bottom).offset(SPACED * 5);
        
    }];
    [self.collectionButton setBackgroundImage:[UIImage imageNamed:@"collection@3x.png"] forState:UIControlStateNormal];
    
    UILabel *collectionLabel  = [[UILabel alloc]init];
    collectionLabel.font = [UIFont systemFontOfSize:15];
    collectionLabel.text = @"我的直播";
    collectionLabel.textAlignment = 1;
    [self.view addSubview:collectionLabel];
    [collectionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(SPACED * 10, SPACED * 4));
        make.centerX.equalTo(self.collectionButton.mas_centerX);
        make.top.equalTo(self.collectionButton.mas_bottom).offset(SPACED);
        
    }];
    
    // 历史记录
    
    self.historyButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_historyButton];
    [self.historyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SPACED * 4, SPACED * 4));
        make.centerX.equalTo(self.view.mas_centerX).offset(self.view.center.x / 2);
        make.top.equalTo(self.defaultLoadImageView.mas_bottom).offset(SPACED * 5);
        
    }];
    [self.historyButton setBackgroundImage:[UIImage imageNamed:@"history@3x.png"] forState:UIControlStateNormal];
    
    UILabel *historyLabel  = [[UILabel alloc]init];
    historyLabel.font = [UIFont systemFontOfSize:15];
    historyLabel.text = @"我的足迹";
    historyLabel.textAlignment = 1;
    [self.view addSubview:historyLabel];
    [historyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(SPACED * 10, SPACED * 4));
        make.centerX.equalTo(self.historyButton.mas_centerX);
        make.top.equalTo(self.historyButton.mas_bottom).offset(SPACED);
        
    }];
    
    
    
}

// 用户名的懒加载
-(UILabel *)userNameLabel{
    
    
    
    if ([[EMClient sharedClient] isLoggedIn])
    {
        
        NSString *userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
        // 判断是否已经有了, 若没有, 则进行实例化
        if (!_userNameLabel)
        {
            
            if (userName != nil)
            {
                _userNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREENWIDTH / 2 - [Tools getTextWidth:userName withFontSize:15] / 2, SPACED * 6, [Tools getTextWidth:userName withFontSize:15] , SPACED * 2)];
                _userNameLabel.textAlignment = 1;
                _userNameLabel.font = [UIFont systemFontOfSize:15];
                [self.view addSubview:_userNameLabel];
            }
        }
        
    }
    return _userNameLabel;
}




-(void)tap{
    
    // 如果没有登录
    if(![EMClient sharedClient].isLoggedIn)
    {
        //跳转到登录和注册界面
        LoadResigter_ViewController *loadResigterVC = [[LoadResigter_ViewController alloc]init];
        [self presentViewController:loadResigterVC animated:YES completion:nil];
        
    }
    else
    {
        HadLogin_ViewController *hadLoginVC = [[HadLogin_ViewController alloc]init];
        UINavigationController *loginNavi = [[UINavigationController alloc]initWithRootViewController:hadLoginVC];
        
        [self presentViewController:loginNavi animated:YES completion:nil];
        
        
    }
    
    
}





-(void)headerIsLoadOrNot{
    
    // 如果没有登录
    if(![EMClient sharedClient].isLoggedIn)
    {
        //跳转到登录和注册界面
        LoadResigter_ViewController *loadResigterVC = [[LoadResigter_ViewController alloc]init];
        [self presentViewController:loadResigterVC animated:YES completion:nil];
        
    }
    else
    {
        HadLogin_ViewController *hadLoginVC = [[HadLogin_ViewController alloc]init];
        UINavigationController *loginNavi = [[UINavigationController alloc]initWithRootViewController:hadLoginVC];
        
        [self presentViewController:loginNavi animated:YES completion:nil];
        
        
    }
    
    
}

-(void)backPop:(UIButton *)backButton{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}









@end


